<?php
/**
 * Created by PhpStorm.
 * User: yxs
 * Date: 2017/4/20
 * Time: 16:29
 */

namespace app\index\controller;

use icontroller\admin\AController;
use model\AdminPower;
use think\Controller;
use think\Db;

class System extends AController
{
    /**
     * 使用RecursiveDirectoryIterator遍历文件，列出所有文件路径
     * @param RecursiveDirectoryIterator $dir 指定了目录的RecursiveDirectoryIterator实例
     * @return array $files 文件列表
     */
    private function get_files($path)
    {
        $files = array();
        $dir = new   \RecursiveDirectoryIterator($path);
        for (; $dir->valid(); $dir->next()) {
            if ($dir->isDir() && !$dir->isDot()) {
                if ($dir->haschildren()) {
                    $files = array_merge($files, \get_files($dir->getChildren()));
                };
            } else if ($dir->isFile()) {
                // $files[] =  $dir->getPathName();
                $files[] = $dir->getBasename(".php");
            }
        }
        return $files;
    }

    // <editor-fold defaultstate="collapsed" desc="添加菜单">
    public function create_menu()
    {
        $dispatch = $this->request->dispatch();
        //$activeRouter = $dispatch['module'][0] . '/' . $dispatch['module'][1] . '/' . $dispatch['module'][2];
        $admin_dir = dirname(__FILE__);
        $wechat_dir = dirname(dirname($admin_dir)) . "/wechat/controller";
        $shop_dir = dirname(dirname($admin_dir)) . "/shop/controller";
        $arr_file = $this->get_files($admin_dir);
        $wechat_file = $this->get_files($wechat_dir);
        $shop_file = $this->get_files($shop_dir);
        $path = [
            "index" => ['module' => $dispatch['module'][0], "controller" => $arr_file],
            "wechat" => ['module' => "wechat", "controller" => $wechat_file],
            "shop" => ['module' => "shop", "controller" => $shop_file]
        ];

        Db::startTrans();

        $domain_result = AdminPower::get(["domain" => "admin"]);
        //$adminPower->where(["domain" => "admin"])->find();

        $domain_id = 0;


        if (empty($domain_result)) {
            $adminPower = new AdminPower();
            $add_data = [
                'name' => "admin",
                "domain" => "admin",
                "parent_id" => 0
            ];

            $result = $adminPower->validate(true)->save($add_data);

            if (empty($result)) {
                Db::rollback();
                print_r("运行出错");
                die();
            }
            $domain_id = $adminPower->id;

        }
        // print_r($domain_result);die();
        foreach ($path as $p) {
            $module_result = AdminPower::get(["domain" => "admin", "module" => $p["module"]]);
            //$adminPower->where(["domain" => "admin", "module" =>$p["module"]])->find();

            if (empty($module_result)) {
                $adminPower = new AdminPower();
                $add_data = [
                    'name' => "admin/" . $p["module"],
                    "domain" => "admin",
                    "module" => $p["module"],
                    'parent_id' => $domain_id
                ];

                $result = $adminPower->validate(true)->save($add_data);

                if (empty($result)) {
                    Db::rollback();
                    print_r("运行出错:" . $adminPower->getError());
                    die();
                }
                $module_id = $adminPower->id;
            } else {
                $module_id = $module_result->id;
            }
            foreach ($p['controller'] as $f) {
                $cls = "app\\" . $p["module"] . "\\controller\\" . $f;
                if (class_exists($cls) && $f != "System") {
                    $controller_result = AdminPower::get(["domain" => "admin", "module" => $p["module"], "controller" => $f]);
                    //$adminPower->where(["domain" => "admin", "module" => $p["module"], "controller" => $f])->find();

                    if (empty($controller_result)) {
                        $adminPower = new AdminPower();
                        $add_data = [
                            'name' => "admin/" . $p["module"] . "/" . $f,
                            "domain" => "admin",
                            "module" => $p["module"],
                            "controller" => $f,
                            'parent_id' => $module_id
                        ];
                        $result = $adminPower->validate(true)->save($add_data);
                        if (empty($result)) {
                            Db::rollback();
                            print_r("运行出错" . $adminPower->getError());
                            die();
                        }
                        $controller_id = $adminPower->id;
                    } else {
                        $controller_id = $controller_result->id;
                    }
                    $reflector = new \ReflectionClass($cls);
                    $methods = $reflector->getMethods(\ReflectionMethod::IS_PUBLIC);//获取方法

                    foreach ($methods as $m) {
                        if ($m->name != "__construct") {
                            $function_result = AdminPower::get(["domain" => "admin", "module" => $p["module"], "controller" => $f, "function" => $m->name]);
                            //$adminPower->where(["domain" => "admin", "module" => $p["module"], "controller" => $f, "function" => $m->name])->find();
                            if (empty($function_result)) {
                                $adminPower = new AdminPower();
                                $add_data = [
                                    'name' => "admin/" . $p["module"] . "/" . $f . "/" . $m->name,
                                    "domain" => "admin",
                                    "module" => $p["module"],
                                    "controller" => $f,
                                    "function" => $m->name,
                                    'parent_id' => $controller_id
                                ];
                                $result = $adminPower->validate(true)->save($add_data);
                                if (empty($result)) {
                                    Db::rollback();
                                    print_r("运行出错" . $adminPower->getError());
                                    die();
                                }
                            }
                        }
                    }
                }
            }
        }
        Db::commit();
      // $this->success("操作完成","");
        print_r("操作完成");
    }
    // </editor-fold>

}